// 与echart3.html连接

// 导入模块
const http = require("http");
const fs = require('fs');
const path = require('path');
const mysql = require('mysql');



//创建server实例和数据库连接实例
const server = http.createServer()
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'supermarket'
});

// 编写服务段处理请求的方式，通过回调函数做回应
server.on("request", (req, res) => {
    let url = req.url
    // url=url.split('?')[0]
    fpath = ''
    if (url == '/datas3') {
        connection.query("select * from staff_view;" , function (err, results, fields) {
            if (err) return console.log(err.message);
            var res3 = {
                'xdatas': [],
                'ydatas': [],
                'zdatas': [],
                'wdatas': [],
                'adatas': [{ value: 1, name: 'boss' },
                { value: 11, name: '理货员' },
                { value: 6, name: '收银员' },],
            }
            for (var i = 0; i < 18; i ++) {
                res3.xdatas.push(results[i].s_id)
                res3.ydatas.push(results[i].s_name)
                res3.zdatas.push(results[i].s_age)
                res3.wdatas.push(results[i].dept)
            }
            res.setHeader('Content-Type', 'application/json', 'charset=utf-8');
            res.end(JSON.stringify(res3));
        })
    } else {
        if (url === '/') {
            fpath = path.join(__dirname, "..\\HTML5\\echart3.html")
        } else {
            fpath = path.join(__dirname, '../admin/', url)
        }
        fs.readFile(fpath, 'utf8', (err, dataStr) => {
            // 读取失败，向客户端响应固定的“错误消息”
            if (err) return res.end('404 Not found.')
            // 读取成功，将读取成功的内容，响应给客户端
            res.end(dataStr)
        })
    }
})
// 对接数据
//设置server端口和server启动时需要开启的一些服务 
server.listen(8070, () => {
    // console.log("请访问:http://localhost:8070")
    connection.connect();
}
)
